package com.saint.swipemenulistview.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.saint.swipemenulistview.R;
import com.saint.swipemenulistview.courier.BaseCommUtils;
import com.saint.swipemenulistview.courier.BaseConfig;
import com.saint.swipemenulistview.courier.BaseConstant;
import com.saint.swipemenulistview.courier.FileUtils;
import com.saint.swipemenulistview.courier.UploadImgUtil;
import com.saint.swipemenulistview.utils.FileUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import id.zelory.compressor.Compressor;

import static android.os.Environment.DIRECTORY_PICTURES;

/**
 * Created by Administrator on 2017/12/22.
 */

public class ImageAct extends BaseActivity {
    public static final String TAG = "ImageAct";
    public static final int REQUEST_CAPTURE = 1;
    public static final int REQUEST_ALBUM = 2;

    @ViewInject(R.id.image_view)
    private ImageView imageView;

    private File imageFile;
    private Uri imageUri;
    private String imagePath;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
            switch (msg.what) {
                case 12:
                    String uploadResult = (String) msg.obj;
                    if (TextUtils.isEmpty(uploadResult)) {
                        Toast.makeText(act, "上传结果为空", Toast.LENGTH_SHORT).show();
                    } else {
                        try {
                            JSONObject object = new JSONObject(uploadResult);
                            int code = object.getInt("code");
                            if (200 == code) {
                                //pictit	String	http://files.kkpbcdn.com/20171223162724_3945.jpg
                                String url = object.getJSONObject("data").getString("pictit");
                                Log.e(TAG, "上传图片结果： " + url);

                                Glide.with(act).load(url).dontAnimate().error(R.mipmap.ic_launcher).into(imageView);

                            } else {
                                Toast.makeText(act, object.getString("message"), Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected int setContent() {
        return R.layout.act_image;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initDate() {

    }

    @Override
    protected void startAct(Activity startAct) {
        intent = new Intent(startAct, ImageAct.class);
        startAct.startActivity(intent);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_camera_btn:
//                getCamera();
                imagePath = FileUtils.getExternalCacheDirectory(act, DIRECTORY_PICTURES).getPath() + "/" + System.currentTimeMillis() + ".jpg";
                BaseCommUtils.getCamera(act, 1, imagePath);
                break;
            case R.id.get_image_btn:
//                takePictureFromAlum();
                BaseCommUtils.getPhoto(act, 2);
                break;

            default:
                break;
        }
    }


    private void getCamera() {
        //采用时间戳命名图片名称,不至于图片名称重复
        String pictureName = System.currentTimeMillis() + ".jpg";
        imageFile = new File(getExternalCacheDir(), pictureName);
        imageUri = Uri.fromFile(imageFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //图片存储的地方.
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        ComponentName componentName = intent.resolveActivity(getPackageManager());
        if (componentName != null) {
            startActivityForResult(intent, REQUEST_CAPTURE);
        }
    }

    //使用隐式意图打开系统相册
    private void takePictureFromAlum() {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("image/*");
//        ComponentName componentName = intent.resolveActivity(getPackageManager());
//        if (componentName != null) {
//            startActivityForResult(intent, REQUEST_ALBUM);
//        }
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//
        act.startActivityForResult(intent, 2);
        Toast.makeText(act, "调用系统相册", Toast.LENGTH_SHORT).show();
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case 1:
//                try {
//                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                    Log.e(TAG, imageUri.getPath());
//                    Log.e(TAG, " 获取图片大小： " + bitmap.getByteCount() / 1024);
//                    File imageFile = new File(imageUri.getPath());
//                    Log.e(TAG, "拍照图片大小： " + android.text.format.Formatter.formatFileSize(act, imageFile.length()) + "   路径： " + imageUri.getPath());
//                    try {
//                        File file = new Compressor(act).compressToFile(imageFile);
//                        Bitmap bitmap1 = new Compressor(act)
//                                .setMaxHeight(1280)
//                                .setMaxWidth(720)
//                                .compressToBitmap(imageFile);
//                        Log.e(TAG, "压缩图片大小： " + android.text.format.Formatter.formatFileSize(act, file.length()) + "   路径： " + file.getAbsolutePath());
//                        Log.e(TAG, "压缩图片高： " + bitmap.getHeight() + "   宽： " + bitmap.getWidth());
//                        imageView.setImageBitmap(bitmap1);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
                imageFile = new File(imagePath);
                Log.e(TAG, "拍照图片大小： " + Formatter.formatFileSize(act, imageFile.length()) + "   路径： " + imagePath);
                uploadFile(imagePath);

                //                } catch (FileNotFoundException e) {
                //                    e.printStackTrace();
                //                }


                break;

            case 2:
                String imagePath = parsePicturePath(act, data.getData());
                File file = new File(imagePath);
                Log.e(TAG, "获取图片大小： " + Formatter.formatFileSize(act, file.length()) + "   路径： " + imagePath);
//                try {
//                    Log.e(TAG, "获取图片大小： " + FileUtil.getFileSize(file) + "   路径： " + imagePath);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                try {
//                    file = new Compressor(act)
////                            .setMaxHeight(1280).setMaxWidth(720)
//                            .compressToFile(file);
//                    Log.e(TAG, "压缩图片大小： " + Formatter.formatFileSize(act, file.length()) + "   路径： " + file.getAbsolutePath());
//                    Bitmap bitmap = new Compressor(act)
////                            .setMaxHeight(1280).setMaxWidth(720)
//                            .compressToBitmap(file);
//                    Log.e(TAG, "压缩图片高： " + bitmap.getHeight() + "   宽： " + bitmap.getWidth());
//                    imageView.setImageBitmap(bitmap);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (NullPointerException e) {
//                    e.printStackTrace();
//
//                    Toast.makeText(act, "选择图片异常，请更换图片", Toast.LENGTH_SHORT).show();
//                }
                uploadFile(imagePath);


                break;

            default:
                break;
        }

    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private String parsePicturePath(Context context, Uri uri) {

        if (null == context || uri == null)
            return null;

        boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentUri
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageDocumentsUri
            if (isExternalStorageDocumentsUri(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] splits = docId.split(":");
                String type = splits[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + File.separator + splits[1];
                }
            }
            // DownloadsDocumentsUri
            else if (isDownloadsDocumentsUri(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaDocumentsUri
            else if (isMediaDocumentsUri(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = "_id=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosContentUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;

    }

    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        String column = "_data";
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            try {
                if (cursor != null)
                    cursor.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    private boolean isExternalStorageDocumentsUri(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private boolean isDownloadsDocumentsUri(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private boolean isMediaDocumentsUri(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private boolean isGooglePhotosContentUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    /**
     * 拍照上传接口
     */
    protected void uploadFile(String imagePath) {
//        File file1 = file;
//        try {
//            if (FileUtil.getFileSize(file) > 500 * 1024) {
//                file = new Compressor(act)
//                        .setMaxWidth(720)
//                        .setMaxHeight(1080)
//                        .compressToFile(file);
//                Log.e(TAG, "压缩图片大小： " + Formatter.formatFileSize(act, file.length()) + "   路径： " + file.getAbsolutePath());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        String requestUrl = BaseConstant.UPLOADPIC_URL
                + "method=kkpb.file_upload.uploadimage"
                + "&token=77243282BC9BA227060729F875820F7C"
                + "&city_id=410100";

        UploadImgUtil.getInstance().uploadFile(act, imagePath, "pic", requestUrl, new UploadImgUtil.OnUploadResult() {
            @Override
            public void onResult(String result) {
                Message msg = handler.obtainMessage();
                msg.what = 12;
                msg.obj = result;
                handler.sendMessage(msg);
                Log.e(TAG, "结果返回执行————————————————" + result);
            }

            @Override
            public void onFileError() {
                Toast.makeText(act, "文件异常，请更换后重试", Toast.LENGTH_SHORT).show();
            }
        });
//
//
//        final File finalFile = file1;
//        new Thread() {
//            @Override
//            public void run() {
//                File file = new File(BaseConfig.BASE_IMG_CACHE
//                        + System.currentTimeMillis() + ".jpg");
//                String RequestURL =
//                        BaseConstant.UPLOADPIC_URL
//                                + "method=kkpb.file_upload.uploadimage"
//                                + "&token=E0473FA5436C038109031652BC6DE216"
//                                + "&city_id=410100";
//                String result = UploadImgUtil.getInstance().uploadFile(file1,
//                        "pic", RequestURL);
//                Message msg = handler.obtainMessage();
//                msg.what = 12;
//                msg.obj = result;
//                handler.sendMessage(msg);
//            }
//        }.start();
    }


}
